import {
  getLeftData
} from '@admin/api/common'
import {
  listToTree
} from '@admin/utils/index'

export default {
  data() {
    return {
      treeData: [],
      treeLoading: true,
      currentTree: {},
      flatData: []
    }
  },
  computed: {
    keyField: function() {
      try {
        return this.treeInfo.keyField || 'ID'
      } catch (e) {
        return ''
      }
    },
    relationField: function() {
      try {
        return this.treeInfo.relationField || ''
      } catch (e) {
        return ''
      }
    }
  },
  methods: {
    getTreeData() {
      const param = {
        pageId: window.$CD.pageId
      }
      this.treeLoading = true
      return getLeftData(param).then(res => {
        // 处理层级关系
        console.log(this.relationField)
        const data = res.data.map((item) => {
          if (this.treeInfo.displayFields && this.treeInfo.displayFields.length) {
            if (this.treeInfo.displayFields.length == 1) {
              item['TREE_UNION_NAME'] = item[this.treeInfo.displayFields[0]]
            } else {
              const subName = item[this.treeInfo.displayFields[1]]
              item['TREE_UNION_NAME'] = item[this.treeInfo.displayFields[0]] + (subName === undefined ? '' : '(' + subName + ')')
            }
          } else {
            item['TREE_UNION_NAME'] = item['NAME']
          }
          return item
        })
        this.flatData = data
        this.treeData = listToTree(data, this.relationField || 'TYPEID', this.keyField || 'ID', ['', '0', null, 'null'])
        this.$store.commit('page/SET_TREES', this.treeData)
      }).finally(() => {
        this.treeLoading = false
      })
    }
  }
}
